//
//  HOAssistantListViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 7/4/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOAssistantListViewController.h"
#import "HORepairerEntity.h"
#import "HOConstants.h"
#import "UIImageView+WebCache.h"
#import "HOImageMgr.h"
#import "HOUtils.h"
#import "HOButton.h"
#import "HORepairerDetailViewController.h"
#import "HORepairerListViewController.h"
#import "HOAssistantEntity.h"
#import "HOReplyListViewController.h"
#import "HOStaticDataMgr.h"
#import "HOButton.h"

@interface HOAssistantListViewController ()<HORepairerListViewControllerDelegate>

@property(nonatomic ,retain)NSMutableArray *assistantIdList;
@end

@implementation HOAssistantListViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	[self initDataSource];
	[self initTableView];
	[self requestData];
}

- (void)dealloc
{
	[self.assistantIdList removeAllObjects];
	self.assistantIdList = nil;
	[super dealloc];
}

- (void)initDataSource
{
	self.assistantIdList = [NSMutableArray array];
}

- (void)requestData
{
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_GetAssistantOrderList,
								  kHO_FIELD_OrderId:[NSNumber numberWithInt:self.orderEntity.orderId]}];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self setNavigationItemTitle:NSLocalizedString(@"协助维修人", @"协助维修人")];
	int myUserId =  [[[HOStaticDataMgr sharedInstance] getUserInfo] getUserId];
	if(self.orderEntity.doneId == myUserId && self.orderEntity.status == HO_REPORT_ORDER_ACCEPTED)
	{
		[self displayRightButtomItemWithTitle:@"添加"];
	}
	self.tabBarController.tabBar.hidden = YES;
}

- (void)rightButtonItemDidClick
{
	HORepairerListViewController *viewCtrl = [[HORepairerListViewController alloc] init];
	viewCtrl.delegate = self;
	viewCtrl.assistantIdList = self.assistantIdList;
	viewCtrl.departmentId = self.departmentId;
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
}

- (void)didSelectRepairer:(HORepairerEntity *)entity
		   withDepartment:(HODepartmentEntity *)departmentEntity
			withFaultType:(HOFaultCategoryEntity *)firstFaultTypeEntity
			withFaultType:(HOFaultCategoryEntity *)secondFaultTypeEntity
{
	if(departmentEntity == nil)
	{
		[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_AddAssistantFault,
									  kHO_FIELD_OrderId:[NSNumber numberWithInt:self.orderEntity.orderId],
									  kHO_FIELD_AssistantUid:[NSNumber numberWithInt:entity.userId]}];
	}
	else
	{
		if(departmentEntity == nil || firstFaultTypeEntity == nil || secondFaultTypeEntity == nil)
			return;
		NSString *faultId = [NSString stringWithFormat:@"%d-%d", firstFaultTypeEntity.faultId, secondFaultTypeEntity.faultId];
		[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_AddAssistantFault,
									  kHO_FIELD_OrderId:[NSNumber numberWithInt:self.orderEntity.orderId],
									  kHO_FIELD_AssistantUid:[NSNumber numberWithInt:entity.userId],
									  kHO_FIELD_DepartmentId:[NSNumber numberWithInt:departmentEntity.departmentId],
									  kHO_FIELD_FaultId:faultId
									  }];
	}
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}
#pragma mark - -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.row == 0)
		return 64;
	else if(indexPath.row == 1)
		return 36;
	return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	NSInteger count = [self.tableViewDataList count];
	[self updateNoResultView:count];
	return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return 2;
}



- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return HO_HORIZONAL_PADDING;
}

//- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//	return [HOUtils defaultOnePixelConversion];
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

	
	CGFloat cellHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
	
	HOAssistantEntity *entity = [self.tableViewDataList objectAtIndex:indexPath.section];
	if(indexPath.row == 0)
	{
		
		static NSString *UIRepairerTableViewCell = @"UIAssistantTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:UIRepairerTableViewCell];
//		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: UIRepairerTableViewCell] autorelease];
			cell.accessoryType = UITableViewCellAccessoryNone;
		}
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		UIImageView *headerImgView = (UIImageView *)[cell viewWithTag:112];
		if(headerImgView == nil)
		{
			headerImgView = [[[UIImageView alloc]
							  initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
													   7,
													   34,
													   34)] autorelease];
			headerImgView.tag = 112;
			[headerImgView.layer setCornerRadius:17];
			[cell.contentView addSubview:headerImgView];
			[headerImgView.layer setMasksToBounds:YES];
		}
		
		
		[headerImgView sd_setImageWithURL:[NSURL URLWithString:entity.headPic] placeholderImage:[[HOImageMgr sharedInstance] getDefaultImage]];
		
		
		UIImageView *workStatusImgView = (UIImageView *)[cell viewWithTag:1115];
		if(workStatusImgView == nil)
		{
			workStatusImgView = [[[UIImageView alloc]
						initWithFrame:CGRectMake(10,
												 10,
												 15,
												 15)] autorelease];
			workStatusImgView.tag = 1115;
//			[cell.contentView addSubview:workStatusImgView];
		}
		if(entity.isWorking)
		{
			workStatusImgView.image = [UIImage imageNamed:@"icon_online"];
		}
		else
		{
			workStatusImgView.image = [UIImage imageNamed:@"icon_offline"];
		}
		
		UILabel *workStatusLbl = (UILabel *)[cell viewWithTag:1123];
		if(workStatusLbl == nil)
		{
			workStatusLbl = [[[UILabel alloc]
						initWithFrame:CGRectMake(12,
												 37,
												 40,
												 22)] autorelease];
			workStatusLbl.tag = 1123;
			[cell.contentView addSubview:workStatusLbl];
			workStatusLbl.textColor = TEXT_COLOR_181818;
			workStatusLbl.font = [UIFont systemFontOfSize:12];
		}
		if(entity.isWorking)
		{
			workStatusLbl.text = @"[在线]";
			workStatusLbl.textColor = UIColorFromRGB(0x0b7f1e);
		}
		else
		{
			workStatusLbl.text = @"[离线]";
			workStatusLbl.textColor = UIColorFromRGB(0xcdcdcd);
		}
		
		UILabel *nameLbl = (UILabel *)[cell viewWithTag:115];
		if(nameLbl == nil)
		{
			nameLbl = [[[UILabel alloc]
						initWithFrame:CGRectMake(54,
												 12,
												 [HOUtils getScreenSize].width - 115,
												 22)] autorelease];
			nameLbl.tag = 115;
			[cell.contentView addSubview:nameLbl];
			nameLbl.textColor = TEXT_COLOR_181818;
			//		nameLbl.layer.borderWidth = 1;
			nameLbl.font = [UIFont systemFontOfSize:14];
		}
		NSString *name = entity.trueName;
		if(entity.assistantUid == 0)
		{
			name = [NSString stringWithFormat:@"%@(其他科室)", entity.departmentName];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			cell.accessoryType = UITableViewCellAccessoryNone;
		}
		if(entity.isMainRepair)
		{
			name = [NSString stringWithFormat:@"%@【主维修人】", entity.trueName];
			cell.selectionStyle = UITableViewCellSelectionStyleGray;
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		}
		nameLbl.text = [NSString stringWithFormat:@"%@", name];
		
		CGSize contentSize = CGSizeZero;//时间文字宽度
		if(IS_LESSTHAN_IOS7)
		{
			contentSize = [name sizeWithFont:[UIFont systemFontOfSize:12.0]];
		}
		else
		{
			contentSize = [name sizeWithAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:15]}];
		}
		
		NSString *comment = [HOUtils getValideString:entity.commentEntity.content];
		
		
		
		UILabel *statusLbl = (UILabel *)[cell viewWithTag:119];
		if(statusLbl == nil)
		{
			statusLbl = [[[UILabel alloc]
						  initWithFrame:CGRectMake(tableView.frame.size.width - 100 - 30,
												   nameLbl.frame.origin.y - 2,
												   100,
												   22)] autorelease];
			statusLbl.tag = 119;
			[cell.contentView addSubview:statusLbl];
			statusLbl.textColor = TEXT_COLOR_666666;
			//		statusLbl.layer.borderWidth = 1;
			statusLbl.textAlignment = NSTextAlignmentRight;
			statusLbl.font = [UIFont systemFontOfSize:13];
			statusLbl.font = [UIFont systemFontOfSize:((IS_IPHONE_4_SCREEN) || (IS_IPHONE_5_SCREEN)) ? 13 : 15];
			[cell.contentView addSubview:statusLbl];
		}
		statusLbl.textColor = [HOUtils getOrderColorWithStatus:entity.status];
		statusLbl.text = [HOUtils getDescribtionWithStatus:entity.status];
		[nameLbl sizeToFit];
		UILabel *commentLbl = (UILabel *)[cell viewWithTag:117];
		if(commentLbl == nil)
		{
			commentLbl = [[[UILabel alloc]
						   initWithFrame:CGRectMake(nameLbl.frame.origin.x,
													nameLbl.frame.origin.y + nameLbl.frame.size.height - 2,
													tableView.frame.size.width - 90,
													40)] autorelease];
			commentLbl.tag = 117;
			[cell.contentView addSubview:commentLbl];
			commentLbl.numberOfLines = 2;
			//		commentLbl.layer.borderWidth = 1;
			commentLbl.textColor = TEXT_COLOR_666666;
			commentLbl.font = [UIFont systemFontOfSize:12];
		}
		if(comment.length == 0)
		{
			comment = @"无回复信息";
		}
		commentLbl.text = [NSString stringWithFormat:@"%@", comment];
		
		return cell;
	}
	else
	{
		
		static NSString *UIButtonTableViewCell = @"UIButtonTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:UIButtonTableViewCell];
//		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: UIButtonTableViewCell] autorelease];
			cell.accessoryType = UITableViewCellAccessoryNone;
		}
		
		
		HOButton *iconImgView = (HOButton *)[cell viewWithTag:118];
		if(iconImgView == nil)
		{
			UIImage *image = [UIImage imageNamed:@"ic-chakanzhuangtai_dadianhua"];
			iconImgView = [[[HOButton alloc]
							initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
													 4,
													 28,
													 28)] autorelease];
			iconImgView.tag = 118;
			[iconImgView setBackgroundImage:image forState:UIControlStateNormal];
			//			iconImgView.layer.borderWidth = 1;
			[iconImgView addTarget:self action:@selector(callPhoneNumber:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:iconImgView];
		}
		iconImgView.data = entity;
		
//		if(entity.virtualCellPhone == nil || entity.virtualCellPhone.length < 2)
//		{
//			iconImgView.hidden = YES;
//		}
//		else
//		{
//			iconImgView.hidden = NO;
//		}
//		
		
		HOButton *delBtn = (HOButton *)[cell viewWithTag:5544];
		if(delBtn == nil)
		{
			delBtn = [[[HOButton alloc]
					   initWithFrame:CGRectMake(tableView.frame.size.width - 180,
												(cellHeight - 26) / 2,
												80,
												26)] autorelease];
			delBtn.tag = 5544;
			[delBtn setTitle:NSLocalizedString(@"撤销协助", @"撤销协助") forState:UIControlStateNormal];
			[delBtn setTitleColor:MAIN_COLOR forState:UIControlStateNormal];
//			[delBtn setBackgroundImage:[HOUtils createImageWithColor:COLOR_RED_fd5f94 forView:delBtn] forState:UIControlStateNormal];
			delBtn.titleLabel.font = [UIFont systemFontOfSize:14];
			delBtn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
			delBtn.layer.cornerRadius = 5;
			[delBtn.layer setMasksToBounds:YES];
			[delBtn addTarget:self action:@selector(removeAssistant:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:delBtn];
		}
		delBtn.data = entity;
		
		HOButton *btn = (HOButton *)[cell viewWithTag:554];
		if(btn == nil)
		{
			btn = [[[HOButton alloc]
					initWithFrame:CGRectMake(tableView.frame.size.width - 90,
											 (cellHeight - 26) / 2,
											 80,
											 26)] autorelease];
			btn.tag = 554;
			[btn setTitle:NSLocalizedString(@"更多回复", @"历史回复") forState:UIControlStateNormal];
			[btn setTitleColor:TEXT_COLOR_666666 forState:UIControlStateNormal];
			btn.titleLabel.font = [UIFont systemFontOfSize:14];
			btn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
			btn.layer.cornerRadius = 5;
			[btn.layer setMasksToBounds:YES];
			[btn addTarget:self action:@selector(viewDetail:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:btn];
		}
		
		btn.data = entity;
//		btn.hidden = entity.commentEntity.content.length == 0;
		
		int myUserId =  [[[HOStaticDataMgr sharedInstance] getUserInfo] getUserId];
		if(self.orderEntity.doneId == myUserId && self.orderEntity.orderId != entity.orderId && self.orderEntity.status <= HO_REPORT_ORDER_ACCEPTED)
		{
			delBtn.hidden = NO;
		}
		else
		{
			delBtn.hidden = YES;
		}
		return cell;
	}
}

- (void)callPhoneNumber:(id)sender
{
	HOButton *btn = (HOButton *)sender;
	HOAssistantEntity *entity = btn.data;
	[HOUtils callPhoneNumber:entity.virtualCellPhone];
	
}

- (void)removeAssistant:(HOButton *)btn
{
	HOAlertView *amAlertView = [[HOAlertView alloc] initWithTitle:NSLocalizedString(@"您确认撤销此协助吗?",  @"您确认撤销此协助吗?")
														  message: nil
														 delegate: self
												cancelButtonTitle:NSLocalizedString(@"取消", @"取消")
												otherButtonTitles:NSLocalizedString(@"确定", @"确定"), nil];
	amAlertView.data = btn.data;
	amAlertView.tag = [kHO_DIALOG_RemoveAssistant integerValue];
	[amAlertView show];
	[amAlertView release];
	
}

- (void)alertView:(HOAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	[super alertView:alertView clickedButtonAtIndex:buttonIndex];
	if(alertView.tag == [kHO_DIALOG_RemoveAssistant integerValue] && buttonIndex == 1)
	{
		HOAssistantEntity *assistantEntity = (HOAssistantEntity *)alertView.data;
		[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_AssistantFaultRevoke,
									  kHO_FIELD_OrderId:[NSNumber numberWithInt:assistantEntity.orderId]}];
	}
}


- (void)viewDetail:(HOButton *)btn
{
	HOReplyListViewController *viewCtrl = [[HOReplyListViewController alloc] init];
	viewCtrl.orderId = self.orderEntity.orderId;
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	HOAssistantEntity *entity = [self.tableViewDataList objectAtIndex:indexPath.section];
	if(entity.assistantUid == 0)
	{
//		[super popupHintView:@"无法查看科室信息"];
		return;
	}
	HORepairerDetailViewController *viewCtrl = [[HORepairerDetailViewController alloc] init];
	viewCtrl.userId = entity.assistantUid;
	viewCtrl.isWorking = entity.isWorking;
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
	
}
#pragma mark - -- tool

- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response isEqualAction:kHO_ACTION_GetAssistantOrderList])
	{
		[self.tableViewDataList removeAllObjects];
		[self.assistantIdList removeAllObjects];
		for(int i = 0; i < [response.dataNode count]; i ++)
		{
			HOAssistantEntity *entity = [[HOAssistantEntity alloc] init];
			[entity parseDic:[response.dataNode objectAtIndex:i]];
			entity.isMainRepair = i == 0;
			[self.tableViewDataList addObject:entity];
			if(![self.assistantIdList containsObject:[NSNumber numberWithInt:[entity getId]]])
			{
				[self.assistantIdList addObject:[NSNumber numberWithInt:[entity getId]]];
			}
			if(![self.assistantIdList containsObject:[NSNumber numberWithInt:entity.departmentId]])
			{
				[self.assistantIdList addObject:[NSNumber numberWithInt:entity.departmentId]];
			}
			[self.assistantIdList addObject:[NSNumber numberWithInt:[[HOStaticDataMgr sharedInstance] getUserInfo].departmentId]];
			[entity release];
		}
		[baseTableview reloadData];
	}
	if([response isEqualAction:kHO_ACTION_AssistantFaultRevoke])
	{
		[self popupHintView:@"撤销协助成功!"];
		[self requestData];
	}
	else if([response isEqualAction:kHO_ACTION_AddAssistantFault])
	{
		[self popupHintView:@"添加成功!"];
		[self requestData];
	}
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

